<template>
  <div>
    <i-panel title="日期选择">
      <div>
        <i-button size="small" @click="onBeginFocus" inline>开始日期</i-button>
        <span style="color: #9b9b9b;margin-left: 2rem;">{{begin_time}}</span>
      </div>
      <div style="width: 100%;">
        <i-button size="small" @click="onEndFocus" inline>结束日期</i-button>
        <span style="color: #9b9b9b;margin-left: 2rem;">{{end_time}}</span>
      </div>
      <button open-type="getUserInfo" @getuserinfo="bindgetuserinfo">
        开始统计
      </button>
    </i-panel>
    <div class="wrap">
      <mpvue-echarts lazyLoad :echarts="echarts" :onInit="handleInit" ref="echarts" />
    </div>
    <van-popup :show="show_popup" bind:close="onClose" position="bottom">
      <van-datetime-picker
        type="datetime"
        :value="currentDate"
        :min-date="minDate"
        @change="onChange"
        @cancel="onCancel"
        @confirm="onConfirm"
      />
    </van-popup>
    <i-toast id="toast" />
  </div>
</template>

<script>
  import * as echarts from 'echarts/dist/echarts.simple.min';
  import mpvueEcharts from 'mpvue-echarts';

  import { getToken } from '@/utils/index';
  import { $Toast} from '../../../static/iview/base/index';

  let chart = null
  export default {
    data () {
      return {
        //微信登录
        canIUse: wx.canIUse('button.open-type.getUserInfo'),

        //时间选择相关
        begin_time_num: 0,
        end_time_num:0,
        begin_time:'开始日期未设置',
        end_time:'结束日期未设置',
        minHour: 10,
        maxHour: 20,
        minDate: new Date(2018, 11, 1).getTime(),
        currentDate: new Date().getTime(),
        show_popup:false,
        begin_or_end:0,//0 无 1 开始 2 结束

        //echart 相关
        option: null,
        echart_data :[
          // {
          //   value: 38,
          //   name: '上海10'
          // }
        ],
        echarts
      }
    },
    components: {
      mpvueEcharts
    },
    methods: {
      bindgetuserinfo(e){
        let _self = this;
        console.log("bindgetuserinfo", e.mp,e.mp.detail.rawData);
        if(e.mp.detail.encryptedData != null){
          let _data = JSON.parse(e.mp.detail.rawData);
          console.log("bindgetuserinfo _data",_data);
          this.$http.post('/users/set_user_info',
            {
              name:_data.nickName,
              city:_data.city,
              sex:_data.gender,
              icon:_data.avatarUrl
            },
            {
              headers:{
                Authorization: getToken()
              }
            })
            .then(function(response){
              _self.handleCount();
            })
            .catch(function(response){
              console.log(response);
            });
        }else{
          console.log("用户不允许获取信息");
        }
      },
      //饼状图相关
      initChart () {
        this.option = {
          backgroundColor: '#ffffff',
          series: [{
            label: {
              normal: {
                fontSize: 14
              }
            },
            type: 'pie',
            center: ['50%', '50%'],
            radius: [0, '60%'],
            data: this.echart_data,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 2, 2, 0.3)'
              }
            }
          }]
        };
        this.$refs.echarts.init()
      },
      handleInit (canvas, width, height) {
        chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart)
        chart.setOption(this.option)
        return chart
      },
      onClose(){
        this.show = false;
      },
      handleCount(){
        if(this.begin_time.length === 0 || this.end_time.length === 0){
          $Toast({
            content: "时间不能为空"
          });
          return;
        }
        if(this.begin_time === this.end_time){
          $Toast({
            content: "开始与结束时间不能一样"
          });
          return;
        }
        if(this.begin_time_num > this.end_time_num){
          $Toast({
            content: "结束时间不能小于开始时间"
          });
          return;
        }
        this.getRecordByTime();
      },
      getRecordByTime(){
        let _self = this;
        this.$http.post('/label/get_record_by_time',
          {
            begin_time:this.begin_time_num/1000,
            end_time:this.end_time_num/1000
          },
          {
            headers:{
              Authorization: getToken()
            }
          })
          .then(function(response){
            console.log("get_record_by_time", response);
            _self.echart_data = response.data.labels;
            _self.initChart();
          })
          .catch(function(response){
            console.log(response);
          });
      },

      //日期输入相关
      onBeginFocus(){
        console.log("onBeginFocus");
        this.show_popup = true;
        this.begin_or_end = 1;
      },
      onEndFocus(){
        // console.log("onEndFocus");
        this.show_popup = true;
        this.begin_or_end = 2;

      },
      onCancel(){
        // console.log("onCancel");
        this.show_popup = false;
        this.begin_or_end = 0;
      },
      onConfirm({mp:{detail}}){
        // console.log("onConfirm",detail);
        this.show_popup = false;

        if(this.begin_or_end === 1){
          this.begin_time_num = parseInt(detail);
          this.begin_time = new Date(parseInt(detail)).toLocaleString().replace(/:\d{1,2}$/,' ');
        }else if(this.begin_or_end === 2){
          this.end_time_num = parseInt(detail);
          this.end_time = new Date(parseInt(detail)).toLocaleString().replace(/:\d{1,2}$/,' ');
        }else{
          this.begin_time = "";
          this.end_time = "";
          this.begin_time_num=0;
          this.end_time_num=0;
        }
        this.begin_or_end = 0;
      },
      onChange(){
        // console.log("onChange");
        this.show = false;
      }
    },
    onShareAppMessage () {}
  }
</script>

<style scoped>
  .wrap {
    width: 100%;
    height: 300px;
  }
</style>
